package cn.zwz.asset.controller;

import cn.hutool.core.io.unit.DataUnit;
import cn.zwz.asset.entity.MedicalAssets;
import cn.zwz.asset.entity.MedicalAssetsOutboundOrder;
import cn.zwz.asset.service.IMedicalAssetsService;
import cn.zwz.asset.service.IMedicalAssetsOutboundOrderService;
import cn.zwz.basics.baseVo.PageVo;
import cn.zwz.basics.baseVo.Result;
import cn.zwz.basics.utils.PageUtil;
import cn.zwz.basics.utils.ResultUtil;
import cn.zwz.data.utils.MailUtils;
import cn.zwz.data.utils.ZwzNullUtils;
import cn.zwz.insurance.entity.Flow;
import cn.zwz.insurance.entity.Roster;
import cn.zwz.insurance.service.IFlowService;
import cn.zwz.insurance.service.IRosterService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.utils.DateUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.security.Principal;
import java.util.Date;

/**
 * @author 郑为中
 */
@RestController
@Api(tags = "医疗资产出库单")
@RequestMapping("/zwz/medicalAssetsOutboundOrder")
@Transactional
public class MedicalAssetsOutboundOrderController {

    @Autowired
    private IMedicalAssetsOutboundOrderService iMedicalAssetsOutboundOrderService;

    @Autowired
    private IMedicalAssetsService iMedicalAssetsService;

    @Autowired
    private IRosterService rosterService;

    @Autowired
    private IFlowService flowService;

    @ApiOperation(value = "查询资产出库清单")
    @RequestMapping(value = "/getByPage", method = RequestMethod.GET)
    public Result<IPage<MedicalAssetsOutboundOrder>> getByPage(@ModelAttribute MedicalAssetsOutboundOrder medicalAssetsOutboundOrder, @ModelAttribute PageVo page){
        QueryWrapper<MedicalAssetsOutboundOrder> qw = new QueryWrapper<>();
        if(!ZwzNullUtils.isNull(medicalAssetsOutboundOrder.getNature())) {
            qw.eq("nature", medicalAssetsOutboundOrder.getNature());
        }
        if(!ZwzNullUtils.isNull(medicalAssetsOutboundOrder.getAssetName())) {
            qw.like("asset_name", medicalAssetsOutboundOrder.getAssetName());
        }
        if(!ZwzNullUtils.isNull(medicalAssetsOutboundOrder.getRecipients())) {
            qw.like("recipients", medicalAssetsOutboundOrder.getRecipients());
        }
        IPage<MedicalAssetsOutboundOrder> data = iMedicalAssetsOutboundOrderService.page(PageUtil.initMpPage(page),qw);
        for (MedicalAssetsOutboundOrder wh : data.getRecords()) {
            MedicalAssets medicalAssets = iMedicalAssetsService.getById(wh.getAssetId());
            wh.setExistNumber(medicalAssets.getExistingNumber().add(wh.getNumber()));
        }
        return new ResultUtil<IPage<MedicalAssetsOutboundOrder>>().setData(data);
    }

    @ApiOperation(value = "资产出库")
    @RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST)
    public Result<MedicalAssetsOutboundOrder> saveOrUpdate(MedicalAssetsOutboundOrder medicalAssetsOutboundOrder,Principal principal){
        MedicalAssetsOutboundOrder oldMedicalAssetsOutboundOrder = iMedicalAssetsOutboundOrderService.getById(medicalAssetsOutboundOrder.getId());
        BigDecimal oldNumber = BigDecimal.ZERO;
        if(oldMedicalAssetsOutboundOrder != null){
            oldNumber = oldMedicalAssetsOutboundOrder.getNumber();
        }
        // outNumber 要出库的数量
        BigDecimal outNumber = medicalAssetsOutboundOrder.getNumber();
        MedicalAssets oldMedicalAssets = iMedicalAssetsService.getById(medicalAssetsOutboundOrder.getAssetId());
        //如果登录人为申请人的话，则需要先判断是否有金额
        Roster roster = new Roster();
        if(medicalAssetsOutboundOrder.getFlag()){
            //判断一下，是否有金额购买
            int num =  outNumber.intValue();
            int price  = medicalAssetsOutboundOrder.getUnitPrice().intValue();
            int sum = num* price;
            QueryWrapper<Roster> wrapper = new QueryWrapper<>();
            wrapper.eq("name",principal.getName());
            roster = rosterService.getOne(wrapper);
            int money = roster.getMoney().intValue();
            if(money<sum){
                return ResultUtil.error("金额不足，请充值后再次购买");
            }else{
                medicalAssetsOutboundOrder.setStatus("等待收货");

            }
        }
        if(oldMedicalAssets != null){
            // newNumber 出库后还有的数量 = 仓库原本还有的数量 - 出库单的出库数量 + 原有出库单的出库数量
            BigDecimal newNumber = oldMedicalAssets.getExistingNumber().subtract(outNumber).add(oldNumber);
            if(newNumber.compareTo(BigDecimal.ZERO) >= 0){
                oldMedicalAssets.setExistingNumber(newNumber);
                iMedicalAssetsService.saveOrUpdate(oldMedicalAssets);
            }else{
                return ResultUtil.error("手慢啦!库存不足!");
            }
        }
        if(iMedicalAssetsOutboundOrderService.saveOrUpdate(medicalAssetsOutboundOrder)){
            if(medicalAssetsOutboundOrder.getFlag()){
                roster.setMoney(roster.getMoney().subtract(outNumber.multiply(medicalAssetsOutboundOrder.getUnitPrice())));
                //增加流水
                Flow flow = new Flow();
                flow.setRosterId(roster.getId());
                flow.setMoney(outNumber.multiply(medicalAssetsOutboundOrder.getUnitPrice()));
                flow.setRemark("购物商品");
                flow.setStatus("支出");
                flowService.save(flow);
            }
            return new ResultUtil<MedicalAssetsOutboundOrder>().setData(medicalAssetsOutboundOrder);
        }
        return ResultUtil.error();
    }

    @ApiOperation(value = "删除资产出库清单")
    @RequestMapping(value = "/delByIds", method = RequestMethod.POST)
    public Result<Object> delAllByIds(@RequestParam String[] ids){
        for(String id : ids){
            MedicalAssetsOutboundOrder medicalAssetsOutboundOrder = iMedicalAssetsOutboundOrderService.getById(id);
            if(medicalAssetsOutboundOrder != null){
                MedicalAssets medicalAssets = iMedicalAssetsService.getById(medicalAssetsOutboundOrder.getAssetId());
                // 出库单删除之后的库存 = 现有库存 + 出库单的资产数量
                BigDecimal newNumber = medicalAssets.getExistingNumber().add(medicalAssetsOutboundOrder.getNumber());
                medicalAssets.setExistingNumber(newNumber);
                iMedicalAssetsService.saveOrUpdate(medicalAssets);
            }
            iMedicalAssetsOutboundOrderService.removeById(id);
        }
        return ResultUtil.success();
    }

    @ApiModelProperty(value = "个人购买明细")
    @RequestMapping(value = "/getByPageByUserId", method = RequestMethod.GET)
    public Result<IPage<MedicalAssetsOutboundOrder>> getByPageByUserId(@ModelAttribute MedicalAssetsOutboundOrder medicalAssetsOutboundOrder,Principal principal, @ModelAttribute PageVo page){
        QueryWrapper<MedicalAssetsOutboundOrder> qw = new QueryWrapper<>();
        qw.eq("recipients",principal.getName());
        if(!ZwzNullUtils.isNull(medicalAssetsOutboundOrder.getNature())) {
            qw.eq("nature", medicalAssetsOutboundOrder.getNature());
        }
        if(!ZwzNullUtils.isNull(medicalAssetsOutboundOrder.getAssetName())) {
            qw.like("asset_name", medicalAssetsOutboundOrder.getAssetName());
        }
        if(!ZwzNullUtils.isNull(medicalAssetsOutboundOrder.getRecipients())) {
            qw.like("recipients", medicalAssetsOutboundOrder.getRecipients());
        }
        IPage<MedicalAssetsOutboundOrder> data = iMedicalAssetsOutboundOrderService.page(PageUtil.initMpPage(page),qw);
        for (MedicalAssetsOutboundOrder wh : data.getRecords()) {
            MedicalAssets medicalAssets = iMedicalAssetsService.getById(wh.getAssetId());
            wh.setExistNumber(medicalAssets.getExistingNumber().add(wh.getNumber()));
        }
        return new ResultUtil<IPage<MedicalAssetsOutboundOrder>>().setData(data);
    }

    @ApiModelProperty(value = "确认收货")
    @RequestMapping(value = "/confirm", method = RequestMethod.GET)
    public Result<Object> confirm(String id){
        MedicalAssetsOutboundOrder medicalAssetsOutboundOrder = iMedicalAssetsOutboundOrderService.getById(id);
        medicalAssetsOutboundOrder.setStatus("已收货");
        medicalAssetsOutboundOrder.setArriveTime(new Date());
        iMedicalAssetsOutboundOrderService.updateById(medicalAssetsOutboundOrder);
        return ResultUtil.success();
    }

    @RequestMapping(value = "/reject",method = RequestMethod.GET)
    public Result<Object> reject(String id){
        MedicalAssetsOutboundOrder medicalAssetsOutboundOrder = iMedicalAssetsOutboundOrderService.getById(id);
        medicalAssetsOutboundOrder.setStatus("申请退货");
        iMedicalAssetsOutboundOrderService.updateById(medicalAssetsOutboundOrder);
        return ResultUtil.success();
    }

    @RequestMapping(value = "/rejectList",method = RequestMethod.GET)
        public  Result<IPage<MedicalAssetsOutboundOrder>> rejectList(@ModelAttribute PageVo page){
        QueryWrapper qw = new QueryWrapper();
        qw.eq("status","申请退货");
        IPage<MedicalAssetsOutboundOrder> data = iMedicalAssetsOutboundOrderService.page(PageUtil.initMpPage(page),qw);
        return new ResultUtil<IPage<MedicalAssetsOutboundOrder>>().setData(data);
        }

    @RequestMapping(value = "/reject1",method = RequestMethod.GET)
        public Result<Object> reject1(String id){
        MedicalAssetsOutboundOrder medicalAssetsOutboundOrder = iMedicalAssetsOutboundOrderService.getById(id);
        medicalAssetsOutboundOrder.setStatus("等待收货");
        String recipientsId = medicalAssetsOutboundOrder.getRecipientsId();
        QueryWrapper<Roster> wrapper = new QueryWrapper();
        wrapper.eq("user_id",recipientsId);
        Roster roster = rosterService.getOne(wrapper);
        iMedicalAssetsOutboundOrderService.updateById(medicalAssetsOutboundOrder);
        rosterService.updateById(roster);
        MailUtils.sendMail
                (roster.getMobile()+"@qq.com","【医疗保险系统】提醒您！您本次退款申请审核失败",
                        "医疗保险系统 退款申请通知");
        return ResultUtil.success();
    }

    @RequestMapping(value = "/agree",method = RequestMethod.GET)
    public Result<Object> agree(String id){
        MedicalAssetsOutboundOrder medicalAssetsOutboundOrder = iMedicalAssetsOutboundOrderService.getById(id);
        medicalAssetsOutboundOrder.setStatus("已退款");
        String recipientsId = medicalAssetsOutboundOrder.getRecipientsId();
        QueryWrapper<Roster> wrapper = new QueryWrapper();
        wrapper.eq("user_id",recipientsId);
        Roster roster = rosterService.getOne(wrapper);
        roster.setMoney(roster.getMoney().add(medicalAssetsOutboundOrder.getUnitPrice().multiply(medicalAssetsOutboundOrder.getNumber())));
        MailUtils.sendMail
                (roster.getMobile()+"@qq.com","【医疗保险系统】提醒您！您退款审批已经完成！这次报销的金额为"+medicalAssetsOutboundOrder.getUnitPrice().multiply(medicalAssetsOutboundOrder.getNumber())+
                                "已经发到您的余额上注意查收",
                        "医疗保险系统 退款申请通知");
        iMedicalAssetsOutboundOrderService.updateById(medicalAssetsOutboundOrder);
        rosterService.updateById(roster);
        Flow flow = new Flow();
        flow.setRosterId(roster.getId());
        flow.setMoney(medicalAssetsOutboundOrder.getUnitPrice().multiply(medicalAssetsOutboundOrder.getNumber()));
        flow.setRemark("商品退款");
        flow.setStatus("收入");
        flowService.save(flow);
        return ResultUtil.success();
    }

}
